from PySide6.QtWidgets import (
    QLabel,
    QLineEdit,
    QPushButton,
    QHBoxLayout,
    QVBoxLayout,
    QListView,
    QListWidget,
    QListWidgetItem,
    QAbstractItemView,
)
from PySide6.QtGui import QPixmap, QIcon
from PySide6.QtCore import Qt, QSize, QUrl, Signal
from PySide6.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
import random


class ShopWindow(QVBoxLayout):
    """收银台"""

    def __init__(self):
        super().__init__()
        self.setContentsMargins(5, 5, 5, 5)
        last_tap = QPushButton()
        last_tap.setIcon(QIcon("static/left.png"))
        last_tap.setStyleSheet(
            """
            QPushButton {background-color:transparent;border:none;height:40px;border-radius:3px;}
            QPushButton:hover {background-color:rgba(255,255,255,0.1);border:none;}
            """
        )
        next_tap = QPushButton()
        next_tap.setIcon(QIcon("static/right.png"))
        next_tap.setStyleSheet(
            """
            QPushButton {background-color:transparent;border:none;height:40px;border-radius:3px;}
            QPushButton:hover {background-color:rgba(255,255,255,0.1);border:none;}
            """
        )
        self.list_tap = tapItemListView()

        h0 = QHBoxLayout()
        h0.setContentsMargins(0, 0, 0, 0)
        h0.addWidget(last_tap)
        h0.addWidget(self.list_tap)
        h0.addWidget(next_tap)
        # ------------------------------
        self.search_bar = QLineEdit()
        self.search_bar.setPlaceholderText("搜索商品条码、简拼、名称")
        self.search_bar.setStyleSheet(
            """
            QLineEdit {color:white;background-color:rgba(255,255,255,0.1);border:none;border-radius:3px;height:30px;padding-left:10px;}
            QLineEdit:hover {background-color:rgba(255,255,255,0.2);border:none;border-radius:3px;}
            """
        )
        self.search_btn = QPushButton("搜索")
        self.search_btn.setStyleSheet(
            """
            QPushButton {height:30px;width:120px;background-color:rgba(255,255,255,0.1);border:none;border-radius:3px;color:white;font-size:14px;}
            QPushButton:hover {background-color:rgba(255,255,255,0.2);border:none;border-radius:3px;}                          
            """
        )

        h1 = QHBoxLayout()
        h1.setContentsMargins(0, 0, 0, 0)
        h1.addWidget(self.search_bar)
        h1.addWidget(self.search_btn)
        # ------------------------------

        self.shop_box = shopItemListView()
        # ------------------------------
        self.addLayout(h0)
        self.addLayout(h1)
        self.addWidget(self.shop_box)
        # self.addStretch(1)

        # 信号与槽
        last_tap.clicked.connect(lambda: self.last_current_next(-1))
        next_tap.clicked.connect(lambda: self.last_current_next(1))
        self.list_tap.current.connect(self.change_tap)

    def last_current_next(self, current):
        """翻页"""
        try:
            row = self.list_tap.currentRow()
            self.list_tap.setCurrentRow(row + current)
        except Exception as e:
            pass

    def reSizeContainer(self, height):
        """调整容器高度"""
        pos = self.shop_box.pos().y()
        self.shop_box.setFixedHeight(height - pos - 10)

    def change_tap(self, e):
        """切换分类"""
        self.shop_box.loadData(e)


class tapItemListView(QListWidget):
    """商品分类"""

    current = Signal(int)

    def __init__(self):
        super().__init__()
        self.setSpacing(1)
        self.setFlow(QListWidget.LeftToRight)
        self.setWrapping(False)
        self.setFixedHeight(46)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        # self.setSelectionMode(QAbstractItemView.SingleSelection)
        # self.setViewMode(QListWidget.IconMode)
        self.setStyleSheet("background-color:transparent;border:none;")
        self.loadData()

    def loadData(self, data=[{"name": f"商品 {i}", "id": i} for i in range(50)]):
        self.clear()
        for item in data:
            self.createItem(item)

    def createItem(self, data):
        """创建对象"""
        item = QListWidgetItem()
        item.setSizeHint(QSize(80, 40))
        self.addItem(item)
        btn = QPushButton(data["name"])  #  btn = QLabel(data["name"])
        btn.setStyleSheet("color:white;background-color:transparent;border:none;")
        btn.clicked.connect(lambda: self.current_tap(data["id"]))
        self.setItemWidget(item, btn)

    def current_tap(self, e):
        """当前选中"""
        self.current.emit(e)


class shopItemListView(QListWidget):
    """商品橱窗"""

    def __init__(self):
        super().__init__()
        self.setSpacing(5)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setSortingEnabled(True)
        self.setAcceptDrops(False)
        self.setDragEnabled(False)
        self.setWrapping(True)
        self.setIconSize(QSize(230, 96))
        self.setViewMode(QListView.IconMode)
        self.setSelectionMode(QAbstractItemView.SingleSelection)
        self.sortItems(Qt.DescendingOrder)
        self.setResizeMode(QListWidget.Adjust)
        self.setStyleSheet("background-color:transparent;")

        # self.loadData()

    def loadData(self, e=0):
        self.clear()
        data = [
            {
                "name": f"商品 {i}",
                "subtitle": "商品简介",
                "unit": "件",
                "offering_price": 20.00,
                "reserve": "10",
                "selling_price": 15.00,
                "image": random.choice(
                    [
                        "http://127.0.0.1:5500/static/images/beixin.jpeg",
                        "http://127.0.0.1:5500/static/images/maojing.jpg",
                    ]
                ),
            }
            for i in range(15)
        ]
        for item in data:
            self.createItem(item)

    def createItem(self, data):
        """创建对象"""
        item = QListWidgetItem()
        item.setSizeHint(QSize(234, 96))
        self.addItem(item)
        self.setItemWidget(item, shopItemWidget(data))


class shopItemWidget(QPushButton):
    """商品价签"""

    def __init__(self, data):
        super().__init__()
        self.data = data
        # self.setFixedSize(234, 96)

        self.image = QLabel()
        self.image.setFixedSize(96, 96)
        self.title = QLabel(data.get("name"))
        self.subtitle = QLabel(data.get("subtitle"))

        self.offering_price = QLabel(f'{data.get("offering_price")}/{data.get("unit")}')
        self.reserve = QLabel(f'{data.get("reserve")}')
        self.selling_price = QLabel(f'{data.get("selling_price")}')
        self.discount = QLabel(
            self.Calculate_discount(
                data.get("offering_price"), data.get("selling_price")
            )
        )

        h2 = QHBoxLayout()
        h2.setContentsMargins(0, 0, 0, 0)
        h2.addWidget(self.offering_price)
        h2.addWidget(self.reserve)

        h3 = QHBoxLayout()
        h3.setContentsMargins(0, 0, 0, 0)
        h3.addWidget(self.selling_price)
        h3.addWidget(self.discount)

        r = QVBoxLayout()
        r.setContentsMargins(0, 0, 0, 0)
        r.addWidget(self.title)
        r.addWidget(self.subtitle)
        r.addLayout(h2)
        r.addLayout(h3)

        h = QHBoxLayout(self)
        h.setContentsMargins(0, 0, 0, 0)
        h.addWidget(self.image)
        h.addLayout(r)

        # self.setStyleSheet(
        #     """
        #     QPushButton {background-color:transparent;border:1px solid rgba(255,255,255,0.1);border-radius:5px;}
        #     QPushButton:hover {background-color:rgba(255,255,255,0.1);border:none;}
        #     """
        # )

        self.manager = QNetworkAccessManager(self)
        self.manager.finished.connect(self.onFinishedLoadingImage)
        self.load_image(data.get("image"))

    def load_image(self, url):
        request = QNetworkRequest(QUrl(url))
        self.manager.get(request)

    def onFinishedLoadingImage(self, reply):
        if reply.error() == QNetworkReply.NoError:
            pixmap = QPixmap()
            pixmap.loadFromData(reply.readAll())
            pixmap = pixmap.scaled(
                96, 96, Qt.IgnoreAspectRatio, Qt.SmoothTransformation
            )
            self.image.setPixmap(pixmap)
            # self.image.resize(pixmap.size())
        else:
            print("Error:", reply.errorString())

    def Calculate_discount(self, p, s):
        """计算折扣"""
        return str(round(p / s * 10, 1))
